package service;

import dao.BaseDao;
import dao.TicketDao;
import dao.TrainDao;
import model.Ticket;
import model.Train;
import model.User;
import dao.UserDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

/**
 * 车票服务类
 */
public class TicketService {
    private TicketDao ticketDao = new TicketDao();
    private TrainDao trainDao = new TrainDao();
    private UserDao userDao = new UserDao();
    private Random random = new Random();
    private Scanner scanner = new Scanner(System.in);

    // 获取所有车票记录，包括已退票的
    public List<Ticket> getAllTickets() {
        return ticketDao.getAllTickets();
    }

    // 购票
    public boolean bookTicket(int userId, int trainId) {
        // 检查列车是否存在
        Train train = trainDao.getById(trainId);
        if (train == null || train.getAvailableSeats() <= 0) {
            return false;
        }

        // 获取用户信息
        User user = userDao.getById(userId);
        if (user == null) {
            return false;
        }

        // 计算票价（成人票与学生票）
        double price = train.getPrice();
        boolean isStudentTicket = false;
        if (user.getAge() <= 18) {
            price = price / 2;
            isStudentTicket = true;
        }

        // 随机选择车厢
        String[] carriages = train.getCarriages();
        int[] carriageSeats = train.getCarriageSeats();

        // 筛选出还有座位的车厢
        int[] availableCarriages = new int[carriages.length];
        int availableCount = 0;
        for (int i = 0; i < carriages.length; i++) {
            if (carriageSeats[i] > 0) {
                availableCarriages[availableCount++] = i;
            }
        }

        if (availableCount == 0) {
            return false; // 无可用车厢（理论上不会发生，因为已检查总座位数）
        }

        // 随机选择一个可用车厢
        int randomCarriageIndex = availableCarriages[random.nextInt(availableCount)];
        String carriage = carriages[randomCarriageIndex];

        // 显示该车厢的可用座位
        System.out.println("已为您分配 " + carriage + " 车厢");
        System.out.println("该车厢可用座位号为：1-" + carriageSeats[randomCarriageIndex]);

        // 让用户选择座位号
        int seatNumber;
        while (true) {
            System.out.print("请选择座位号 (1-" + carriageSeats[randomCarriageIndex] + "): ");
            if (scanner.hasNextInt()) {
                seatNumber = scanner.nextInt();
                if (seatNumber >= 1 && seatNumber <= carriageSeats[randomCarriageIndex]) {
                    break;
                }
            } else {
                scanner.next(); // 消耗无效输入
            }
            System.out.println("无效的座位号，请重新输入！");
        }
        scanner.nextLine(); // 消耗换行符


        // 创建车票
        String seatStr = carriage + "车厢 " + seatNumber + "号";
        Ticket ticket = new Ticket(userId, trainId, seatStr, new Date(), price, isStudentTicket);
        boolean success = ticketDao.addTicket(ticket);

        // 更新列车座位数
        if (success) {
            // 减少对应车厢的座位数
            carriageSeats[randomCarriageIndex]--;
            // 更新车厢座位信息到数据库
            updateCarriageSeats(trainId, carriageSeats);
            // 更新总座位数
            return trainDao.updateSeats(trainId, train.getAvailableSeats() - 1);
        }
        return false;
    }

    // 更新车厢座位信息到数据库
    private boolean updateCarriageSeats(int trainId, int[] carriageSeats) {
        StringBuilder seatsStr = new StringBuilder();
        for (int i = 0; i < carriageSeats.length; i++) {
            seatsStr.append(carriageSeats[i]);
            if (i < carriageSeats.length - 1) {
                seatsStr.append(",");
            }
        }

        String sql = "UPDATE trains SET 车厢座位信息 = ? WHERE id = ?";
        try (Connection conn = BaseDao.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, seatsStr.toString());
            pstmt.setInt(2, trainId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取用户车票
    public List<Ticket> getUserTickets(int userId) {
        return ticketDao.getByUserId(userId);
    }

    // 退票
    public boolean cancelTicket(int ticketId) {
        // 先获取车票信息
        Ticket ticket = ticketDao.getById(ticketId);
        if (ticket == null || ticket.isCancelled()) {
            return false; // 车票不存在或已取消
        }

        // 获取列车信息
        Train train = trainDao.getById(ticket.getTrainId());
        if (train == null) {
            return false; // 列车不存在
        }

        // 开始事务
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false); // 开启事务

            // 取消车票
            boolean success = ticketDao.cancelTicket(conn, ticketId);
            if (!success) {
                conn.rollback();
                return false;
            }

            // 解析座位信息，提取车厢和座位号
            String seatStr = ticket.getSeatNumber(); // 格式如 "B车厢 15号"
            String carriage = seatStr.substring(0, 1); // 获取车厢字母
            String[] carriages = train.getCarriages();
            int carriageIndex = -1;

            // 查找车厢索引
            for (int i = 0; i < carriages.length; i++) {
                if (carriages[i].equals(carriage)) {
                    carriageIndex = i;
                    break;
                }
            }

            if (carriageIndex == -1) {
                conn.rollback();
                return false; // 无效的车厢信息
            }

            // 增加对应车厢的座位数
            int[] carriageSeats = train.getCarriageSeats();
            carriageSeats[carriageIndex]++;

            // 更新车厢座位信息
            if (!updateCarriageSeats(conn, train.getId(), carriageSeats)) {
                conn.rollback();
                return false;
            }

            // 更新列车总座位数
            if (!trainDao.updateSeats(conn, train.getId(), train.getAvailableSeats() + 1)) {
                conn.rollback();
                return false;
            }

            // 提交事务
            conn.commit();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            return false;
        } finally {
            BaseDao.close(conn, null, null);
        }
    }

    // 更新车厢座位信息到数据库
    private boolean updateCarriageSeats(Connection conn, int trainId, int[] carriageSeats) {
        StringBuilder seatsStr = new StringBuilder();
        for (int i = 0; i < carriageSeats.length; i++) {
            seatsStr.append(carriageSeats[i]);
            if (i < carriageSeats.length - 1) {
                seatsStr.append(",");
            }
        }

        String sql = "UPDATE trains SET 车厢座位信息 = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, seatsStr.toString());
            pstmt.setInt(2, trainId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}